package flexexamples.logging
{
	import mx.messaging.ChannelSet;
	import mx.messaging.channels.AMFChannel;
	import mx.messaging.channels.SecureAMFChannel;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.remoting.RemoteObject;
	
	import org.as3commons.logging.ILogger;
	import org.as3commons.logging.ILoggerFactory;

	public class RemoteLoggerFactory implements ILoggerFactory
	{
		private var remote:RemoteObject;
		
		public function RemoteLoggerFactory(url:String, destination:String="remoteObjectLogger", fault:Function=null)
		{
			remote = createRemote(url, destination);
			remote.addEventListener(FaultEvent.FAULT, fault == null ? onRemoteFault:fault);	
		}

		public function getLogger(name:String):ILogger
		{
			return new RemoteLogger(name, remote);
		}
		
		/** Creates a RemoteObject using SecureAMFChannel if https */
		private function createRemote(url:String, destination:String) : RemoteObject
		{
			var channelSet:ChannelSet = new ChannelSet();
			channelSet.addChannel(isHttps(url) ? new SecureAMFChannel(null, url) : new AMFChannel(null, url));
			
			var remoteService:RemoteObject = new RemoteObject(destination);
			remoteService.channelSet = channelSet;
			
			return remoteService;
		}
		
		private function isHttps(url:String) : Boolean
		{
			return url.indexOf("https") != -1;
		}
		
		/** Default FaultHandler. Just traces the message. */
		private function onRemoteFault(evt:FaultEvent) : void
        {
        	trace("Could not log to server: "+evt.fault.message);
        }
        
	}
}